/*
 * 本类作用：mina框架:编码器，用于发送数据时打包
 * 
 * 作者：袁小杰
 * 博客：http://blog.csdn.net/undoner
 * GIT：https://git.oschina.net/undoner
 * QQ：15137281
 * 
 */
package com.smforj.ssm.mina.codec;

import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/***
 * 编码器，用于发送数据时打包
 * 针对SIP2
 * 
 * @author Haijun Gao 
 * @date 2016-7-28 上午8:49:56
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
public class MsgEncoder extends ProtocolEncoderAdapter {

	private final Charset charset;

	static Logger log = Logger.getRootLogger();

	public MsgEncoder(Charset charset) {
		this.charset = charset;
	}

	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {
		log.debug("MsgEncoder.encode()");  
		// 将message转换为实体对象
		MsgEntity me = (MsgEntity) message; 
		IoBuffer ib = null;
		if(me.getContent() != null && me.getContent().length() > 0)
		{
			System.out.println("MsgEncoder.encode(): "+me.getContent());
			// 声明IoBuffer
			ib = IoBuffer.allocate(me.getContent().length()); 
			// 设置IoBuffer可自动扩展
			ib.setAutoExpand(true);  
			// 写正文
			if (me.getContent() != null) { 
				byte[] data = me.getContent().startsWith("p<<?xml") ? me.getContent().getBytes(charset) : MsgUtils.stringToBytes(me.getContent());
				System.out.println("编码后数据："+data.length);
				ib.put(data); 
			}
		}else
		{
			System.out.println("MsgEncoder.encode(): "+me.getData().length);
			// 声明IoBuffer
			ib = IoBuffer.allocate(me.getData().length); 
			// 设置IoBuffer可自动扩展
			ib.setAutoExpand(true);  
			// 写正文  
		    ib.put(me.getData());  
		} 
		// 重设IoBuffer的指针，到头
		ib.flip(); 
		out.write(ib); 
	}
	
}
